const app = getApp()
const i18n = require('../../../utils/i18n/index')

Page({
  data: {
    form: {
      type: 0,
      category_ids: '',
      title: '',
      content: '',
      title_en: '',
      content_en: '',
      company: '',
      images: [],
    },
    id: 0,
    selectCategoryIndex:'',
    detail: {},
    types: [
      { id: 0, name: '供应', name_en: 'Supply' },
      { id: 1, name: '需求', name_en: 'Demand' }
    ],
    categories: [],
    cdnUrl: '',
    locale: 'zh_CN',
    t: {},
    showProfileForm: false,
    userInfo: null
  },
  onEdit() {
    const editId = wx.getStorageSync('needEditId') || ''
    console.log('init',editId)
    this.setData({
        id:editId
    })
    this.loadDetail()
  },
  onShow() {
    //wx.removeStorageSync('needEditId')
    // 更新导航栏标题
    wx.setNavigationBarTitle({
        title: i18n.getLocale()=='en_US'?'Publish':'发布供需'
    });

    getApp().loadUserInfo()
    setTimeout(() => {
        if (!app.globalData.isLogin) {
            wx.showModal({
              title: '提示',
              content: '请先登录后再操作',
              success: (res) => {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/mine/login/login'
                  })
                }
              }
            })
            return
          }
          this.setData({
            userInfo: app.globalData.userInfo,
            'form.company':app.globalData.userInfo.company
          })
        if (app.globalData.userInfo.company == "") {
            wx.showModal({
                title: '提示',
                content: '请补充完整个人信息',
                success: (res) => {
                if (res.confirm) {
                    wx.navigateTo({
                    url: '/pages/mine/profile/profile'
                    })
                }
                }
            })
            return
        }
    },1000)
  },

  onLoad() {
    this.setData({
      cdnUrl: app.globalData.cdnUrl
    })
    this.setI18nData()
    this.loadCategories()
    this.checkUserProfile()
    //this.loadDetail()
    // 监听语言变更事件
    const self = this
    app.globalData.eventBus.on('localeChanged', function() {
      self.setI18nData()
    })
  },

  setI18nData() {
    this.setData({
      locale: i18n.getLocale(),
      t: {
        title: i18n.t('supply.publish.title'),
        type: i18n.t('supply.publish.type'),
        category: i18n.t('supply.publish.category'),
        title: i18n.t('supply.publish.title'),
        titleZh: i18n.t('supply.publish.titleZh'),
        titleEn: i18n.t('supply.publish.titleEn'),
        content: i18n.t('supply.publish.content'),
        desc: i18n.t('supply.publish.desc'),
        descZh: i18n.t('supply.publish.descZh'),
        descEn: i18n.t('supply.publish.descEn'),
        contact: i18n.t('supply.publish.contact'),
        contactName: i18n.t('supply.publish.contactName'),
        contactPhone: i18n.t('supply.publish.contactPhone'),
        images: i18n.t('supply.publish.images'),
        submit: i18n.t('supply.publish.submit'),
        typePlaceholder: i18n.t('supply.publish.typePlaceholder'),
        categoryPlaceholder: i18n.t('supply.publish.categoryPlaceholder'),
        titleZhPlaceholder: i18n.t('supply.publish.titleZhPlaceholder'),
        titleEnPlaceholder: i18n.t('supply.publish.titleEnPlaceholder'),
        descZhPlaceholder: i18n.t('supply.publish.descZhPlaceholder'),
        descEnPlaceholder: i18n.t('supply.publish.descEnPlaceholder'),
        contactNamePlaceholder: i18n.t('supply.publish.contactNamePlaceholder'),
        contactPhonePlaceholder: i18n.t('supply.publish.contactPhonePlaceholder'),
        uploadImage: i18n.t('supply.publish.uploadImage'),
        maxImages: i18n.t('supply.publish.maxImages'),
        uploading: i18n.t('supply.publish.uploading'),
        uploadFailed: i18n.t('supply.publish.uploadFailed'),
        incomplete: i18n.t('supply.publish.incomplete'),
        submitSuccess: i18n.t('supply.publish.submitSuccess'),
        submitFail: i18n.t('supply.publish.submitFail'),
        completeProfile: i18n.t('publish.completeProfile'),
        avatar: i18n.t('publish.avatar'),
        name: i18n.t('publish.name'),
        namePlaceholder: i18n.t('publish.namePlaceholder'),
        gender: i18n.t('publish.gender'),
        male: i18n.t('publish.male'),
        female: i18n.t('publish.female'),
        company: i18n.t('supply.publish.company'),
        companyPlaceholder: i18n.t('supply.publish.companyPlaceholder'),
        position: i18n.t('publish.position'),
        positionPlaceholder: i18n.t('publish.positionPlaceholder'),
        confirm: i18n.t('publish.confirm')
      }
    })
   
  },

  onLanguageChange() {
    this.setI18nData()
  },

  // 加载详情
  loadDetail() {
      if (this.data.id == 0) {
          console.log('无id')
          return
      }
      console.log('id是多少',this.data.id)
    wx.request({
      url: app.globalData.baseUrl + 'public/needs/' + this.data.id,
      data: { 
      },
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: res => {
        if (res.data.code === 0) {

            const detail = res.data.data.needs
            this.setData({
            'form.title': detail.title,
            'form.type': detail.type,
            'form.content': detail.content,
            'form.company': detail.company,
            //'form.category_ids': detail.categories[0].id,
            'form.images': detail.images
            })

            const categories = this.data.categories
            categories.map(item => {
              item.show = false;
              detail.categories.forEach(itemSelected => {
                if (item.id == itemSelected.id) {
                  item.show = true;
                }
              })
              return item;
            })

          this.setData({
            categories: categories|| [],
            detail: detail,
            isInterested: res.data.data.is_interested
          })
        }
      }
    })
  },

  // 加载分类
  loadCategories() {
    wx.request({
      url: app.globalData.baseUrl + 'public/categories',
      success: res => {
        if (res.data.code === 0) {
          const categories = res.data.data.categories
          
          this.setData({
            categories: categories|| []
          })
        }
      }
    })
  },

  // 选择类型
  onTypeChange(e) {
    this.setData({
      'form.type': this.data.types[e.detail.value].id
    })
  },

  // 选择分类
  onCategoryChange(e) {
    this.setData({
      'selectCategoryIndex':e.detail.value,
      'form.category_ids':this.data.categories[e.detail.value].id
    })
  },

  onCategorySelect: function(e) {
    const data = e.currentTarget.dataset
    const categories = this.data.categories
    categories[data.index].show = !categories[data.index].show
    this.setData({
        categories:categories
    })
},

  // 输入处理
  onInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`form.${field}`]: e.detail.value
    })
  },

  // 选择图片
  chooseImage() {
    const count = 9 - this.data.form.images.length
    if (count <= 0) {
      wx.showToast({
        title: this.data.t.maxImages,
        icon: 'none'
      })
      return
    }

    wx.chooseMedia({
      count,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tasks = res.tempFiles.map(file => this.uploadImage(file))
        Promise.all(tasks).then(() => {
          wx.hideLoading()
        })
      }
    })
  },

  // 上传图片
  uploadImage(file) {
    wx.showLoading({ title: this.data.t.uploading })
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: app.globalData.baseUrl + 'api/upload',
        filePath: file.tempFilePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${app.globalData.token}`
        },
        success: res => {
          const data = JSON.parse(res.data)
          if (data.code === 0) {
            this.setData({
              'form.images': [...this.data.form.images, data.url]
            })
            resolve()
          } else {
            wx.showToast({
              title: this.data.t.uploadFailed,
              icon: 'none'
            })
            reject()
          }
        },
        fail: () => {
          wx.showToast({
            title: this.data.t.uploadFailed,
            icon: 'none'
          })
          reject()
        }
      })
    })
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = [...this.data.form.images]
    images.splice(index, 1)
    this.setData({
      'form.images': images
    })
  },

  // 预览图片
  previewImage(e) {
    const { url } = e.currentTarget.dataset
    wx.previewImage({
      current: url,
      urls: this.data.form.images
    })
  },

  // 提交表单
  onSubmit() {
    const { form } = this.data
    /*if (Array.isArray(form.images)) {
      form.images = form.images.join(',')
    }*/

    const categories = this.data.categories
    const category_ids = []
    categories.forEach(item => {
        if (item.show) {
            category_ids.push(item.id)
        }
    })
    this.setData({
      'form.category_ids':category_ids.join(',')
    })

    console.log(form)
    // 表单验证
    if (!form.category_ids || !form.title || !form.content || !form.company) {
      wx.showToast({
        title: this.data.t.incomplete,
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: i18n.t('common.loading') })

    wx.request({
      url: app.globalData.baseUrl + 'api/post?id='+this.data.id,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      data: form,
      success: res => {
        if (res.statusCode == 401) {
            this.onLogout()
        }
        if (res.data.code === 0) {
          wx.removeStorageSync('needEditId')
          wx.showModal({
            title: '提示',  // 模态框标题
            content: this.data.t.submitSuccess,  // 你要显示的长内容
            showCancel: false,  // 是否显示取消按钮
            confirmText: '确定',  // 确认按钮的文字
            success: function(res) {
              if (res.confirm) {
                // 用户点击了确定按钮的回调
                wx.reLaunch({
                    url: '/pages/supply/my/my',
                  });
              }
            }
          });
          
        } else {
          wx.showModal({
            title: '提示',  // 模态框标题
            content: res.data.msg,  // 你要显示的长内容
            showCancel: false,  // 是否显示取消按钮
            confirmText: '确定',  // 确认按钮的文字
            success: function(res) {
              if (res.confirm) {
                // 用户点击了确定按钮的回调
              }
            }
          });

          if (res.data.code == 110) {
            setTimeout(() => {
                //wx.navigateBack()
                wx.navigateTo({
                    url: '/pages/mine/profile/profile'
                })
              }, 2000)
          }
        }
      },
      fail: () => {
        wx.showToast({
          title: this.data.t.submitFail,
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  checkUserProfile() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo.name) {
      this.setData({
        showProfileForm: true
      })
    } else {
      this.setData({
        userInfo
      })
    }
  },

  // 选择头像
  onChooseAvatar(e) {
    this.setData({
      'userInfo.avatarUrl': e.detail.avatarUrl
    })
  },

  // 提交个人信息
  submitProfile(e) {
    const values = e.detail.value
    const { avatarUrl } = this.data.userInfo

    if (!avatarUrl) {
      return wx.showToast({
        title: '请选择头像',
        icon: 'none'
      })
    }

    if (!values.name) {
      return wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
    }

    if (!values.gender) {
      return wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
    }

    if (!values.company) {
      return wx.showToast({
        title: '请输入单位名称',
        icon: 'none'
      })
    }

    if (!values.position) {
      return wx.showToast({
        title: '请输入单位职务',
        icon: 'none'
      })
    }

    wx.showLoading({
      title: '保存中...',
      mask: true
    })

    // 先上传头像
    wx.uploadFile({
      url: app.globalData.baseUrl + 'api/upload',
      filePath: avatarUrl,
      name: 'file',
      success: res => {
        const data = JSON.parse(res.data)
        if (data.code === 0) {
          // 保存用户信息
          wx.request({
            url: app.globalData.baseUrl + 'user/profile',
            method: 'POST',
            data: {
              ...values,
              avatar_url: data.data.url
            },
            success: res => {
              if (res.data.code === 0) {
                const userInfo = {
                  ...values,
                  avatar_url: data.data.url
                }
                wx.setStorageSync('userInfo', userInfo)
                this.setData({
                  userInfo,
                  showProfileForm: false
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            }
          })
        }
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 供需类型单选点击
  onTypeRadioChange(e) {
    const id = e.currentTarget.dataset.id
    this.setData({
      'form.type': id
    })
  },

  // 注销
  onLogout() {
    wx.removeStorageSync('token')
    app.globalData.token = ''
    app.globalData.isLogin = false
    this.setData({
      isLogin: false,
      userInfo: null
    })
    wx.navigateTo({
        url: '/pages/mine/login/login'
    })
  }
}) 